<!--
* @Description: indicatorMonitoring.vue
* @Author: 王燕欣 指标监控
* @Date: 2024-10-19 11:13
-->
<template>
  <div class="ku_table_content" @scroll="handleScroll">
    <!-- <div class="ku_button ku_button_plain_primary" @click="simulatedSideSearch">
      模拟搜索
    </div> -->
    <table :style="{width: tableWidth}">
      <thead :class="scrollState?'ku_table_scroll':''">
        <tr>
          <th v-for="(item ,index) in columns" :key="index" :width="item.width+'px'">{{ item.title }}</th>
        </tr>
      </thead>
      <tbody v-if="processedTableData.length>0">
        <tr v-for="(row,rowindex) in processedTableData" :key="rowindex">
          <td v-for="(item ,key,index) in row" :key="index">
            <div v-if="key==='diffSeq'" :class="row.diffSeq < 0 ? 'ku_text_danger':row.diffSeq > 0 ? 'ku_text_primary':''">
              {{ item }}
            </div>
            <div v-else-if="key==='planSeq'" :class="row.diffSeq < 0 ? 'ku_text_danger':row.diffSeq > 0 ? 'ku_text_primary':''">
              {{ item }}
            </div>
            <div v-else>{{ item }}</div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import dayjs from "dayjs";
import { cloneDeep } from "lodash";
import globalConfigs from "@/utils/globalConfigs";
import { getGovernmentIndicatorsListApi, getAuthRouteListApi } from "@/api/base";
import FlutterBridge from "@/utils/FlutterBridge";
import $store from '@/store'
import { setTimeout } from "core-js";
export default {
  name: "indicatorMonitoring",
  components: {

  },
  props: {},

  data() {
    return {
      tableWidth: "1200px",
      scrollState: false, // 是否滚动
      columns: [
        { field: 'routeName', title: '线路名称', width: 200 },
        { field: 'runDirection', title: '开往方向', width: 250 },
        { field: 'govtSeq', title: '政府最低要求班次', width: 200 },
        { field: 'planSeq', title: '当日计划班次', width: 150 },
        { field: 'diffSeq', title: '班次偏差', width: 100 },
        { field: 'realSeq', title: '实时班次数量', width: 150 },
        { field: 'overSeq', title: '中途插入班次', width: 150 },
      ],
      processedTableData: [], // 处理后的数据


      currentRoute: [],// 当前线路
      rawData: [], // 原始数据

      getInterval: null, // 定时获取数据
    };
  },
  watch: {
    '$store.state.user.token': {
      handler(newVal, oldVal) {
        console.log('watch--监听-newVal--->store.token---', newVal);
        console.log('watch--监听--old--->store.token-2--', oldVal);
        if (newVal) {
          console.log('token------>', $store.state.user.token);
          this.$nextTick(async () => {
            await this.getAuthRouteListFun();
            this.getGovernmentIndicatorsListFun();
          });
        }
      },
      deep: true, //  深度监听
      immediate: true, // 立即执行
    },
    '$store.state.user.rightSideSearchIndicatorMonitoring': {
      handler(newVal) {
        if (newVal) {
          console.log('rightSideSearch------>');
          this.rightSideSearchCallback(newVal);
        }
      },
      deep: true, //  深度监听
      immediate: true, // 立即执行
    },
  },
  mounted() {
    let _this = this;
    // 判断是否是
    if (globalConfigs.IS_DEV) {
      this.$nextTick(async () => {
        await this.getAuthRouteListFun();
        this.getGovernmentIndicatorsListFun();
      });
    } else {
      FlutterBridge.RequestFlutterBridge('getTokenFromFlutter');// 从flutter获取token
      window.FlutterBridgeCallback = FlutterBridge.FlutterBridgeCallback; // 监听flutter回掉方法
    }
    // 定时器60秒获取一次数据
    this.getInterval = window.setInterval(function () {
      _this.getGovernmentIndicatorsListFun();
    }, 1000 * 60 * 5);
  },
  beforeDestroy() {
    // 销毁定时器
    console.log('销毁定时器');
    window.clearInterval(this.getInterval);
    this.getInterval = null;
  },

  methods: {
    /**
   * @Description: 模拟Flutter 数据 回调方法
   * @Author: 王燕欣
   * @Date: 2025-01-20 14:09
   */
    simulatedSideSearch() {
      let prames =
      {
        "method": "rightSideSearch",
        "data": {
          "routeId": "115",
          "routeName": "115",
          "routeType": "2",
          "stopMinutes": null,
          "crossTime": null,
          "crossTimestamp": null,
          "mainStationName": null,
          "mainEndStationName": null,
          "subStationName": null,
          "subEndStationName": null,
          "segmentCount": null,
          "sortNo": null,
          "displayOrder": null,
          "segmentIdList": [
            "11240103",
            "18243807"
          ]
        },
        "type": "zhibiao"
      }
      prames = JSON.stringify(prames)
      FlutterBridge.FlutterBridgeCallback(prames)
    },

    /**
    * @Description: flutter 搜索回调事件
    * @Author: 王燕欣
    * @Date: 2025-01-20 17:39
    */

    rightSideSearchCallback(params) {
      try {
        let resData = params.data;
        console.log('flutter 搜索回调事件-----rightSideSearchCallback---res-', resData);
        console.log('processedTableData------>', this.processedTableData)
        if (!resData.routeId) {
          this.getGovernmentIndicatorsListFun();
        } else {
          this.processedTableData = this.processedTableData.filter(item => {
            return item.routeId === resData.routeId;
          })
        }
      } catch (error) {
        console.error('flutter 搜索回调事件---rightSideSearchCallback----', error)

      }
    },
    /**
    * @Description: 监测table是否滚动，滚动则把头部颜色变色
    * @Author: 王燕欣
    * @Date: 2025-01-07 09:24
    */
    handleScroll(event) {
      // 获取滚动容器的scrollTop值
      const scrollTop = event.target.scrollTop;
      // 处理滚动事件
      if (scrollTop > 0) {
        this.scrollState = true;
      } else {
        this.scrollState = false;
      }
    },
    /**
    * @Description: 加载更多方法
    * @Author: 王燕欣
    * @Date: 2024-10-19 13:37
    */
    onLoadMore() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        this.finished = true;
      }, 5000)
    },

    /**
     * @Description: 获取线路列表
     * @Author: 王燕欣
     * @Date: 2024-09-27 11:17
     */
    async getAuthRouteListFun() {
      const prames = {};
      let routerList = [];
      await getAuthRouteListApi(prames).then((res) => {
        console.log('获取线路列表--->', res)
        for (let x = 0; x < res.data.length; x++) {
          const itemX = res.data[x];
          routerList.push(itemX.routeId)
        }
        this.currentRoute = routerList;
      });
    },

    /**
    * @Description: 获取指标监控
    * @Author: 王燕欣
    * @Date: 2024-10-26 15:18
    */

    async getGovernmentIndicatorsListFun() {
      let params = {
        routeIdList: this.currentRoute,
        runDate: dayjs().format("YYYY-MM-DD"),
      }
      await getGovernmentIndicatorsListApi(params).then((res) => {
        if (res.code === 200) {
          this.rawData = cloneDeep(res.data);
        }

        console.log('获取指标监控------>', res);
      });
      this.processedTableData = await this.processingDataFun();
      console.log('获取指标监控---processedTableData--->', this.processedTableData);
    },

    // 数据处理，根据
    async processingDataFun() {

      // const viewportWidth = document.documentElement.clientWidth;
      // 获取array1中所有field属性
      const fieldsToKeep = this.columns.map((item) => item.field);
      let temporaryTableWidth = 0;
      for (let x = 0; x < this.columns.length; x++) {
        const item = this.columns[x];
        temporaryTableWidth += parseInt(item.width)
      }
      this.tableWidth = temporaryTableWidth + 'px';
      // if (temporaryTableWidth < viewportWidth) {
      //   this.tableWidth = "100%";
      // } else {

      // }

      // 筛选并构建新对象
      let cloneDeepTable = cloneDeep(this.rawData);
      return cloneDeepTable.map((item) => {
        item.actDateTime = dayjs(item.actDateTime).format("HH:mm:ss");// 处理时间数据
        item.addGpsMile = Number(item.addGpsMile).toString() === "NaN" ? '' : (Number(item.addGpsMile) / 1000).toFixed(2);// 处理里程数据
        const filteredItem = {};
        fieldsToKeep.forEach((field) => {
          if (Object.prototype.hasOwnProperty.call(item, field)) {
            // 检查字段是否存在
            filteredItem[field] = item[field]; // 只保留指定字段
          }
        });
        return filteredItem;
      });
    },

    /**
    * @Description: 页码切换
    * @Author: 王燕欣
    * @Date: 2024-10-18 19:28
    */
    pageChange({ currentPage, pageSize }) {
      this.tablePaging.pageNum = currentPage;
      this.tablePaging.pageSize = pageSize;
      // this.queryVoipOperationRecord();
    },

    filterChangeEvent({ values }) {
      return new Promise(resolve => {
        console.log('values', values);
        let temporaryData = cloneDeep(this.rawData);
        let rest = [];
        if (values.length) {
          switch (values[0]) {
            case 'lt': // 小于
              rest = temporaryData.filter(item => item.diffSeq < 0);
              break;
            case 'gt': // 大于
              rest = temporaryData.filter(item => item.diffSeq > 0);
              break;

            default:
              break;
          }
          this.gridOptions.data = rest;
          resolve(rest)
        } else {
          resolve(temporaryData)

        }
      })
    },
  },
};
</script>
<style lang="sass" scoped>
</style>
